<?php
declare (strict_types=1);
/**
 * @Description:
 * @Author: Chern
 * @Date: 2023/6/30
 * @Time: 11:51
 */

namespace app\model;

use app\stateData;
use think\Model;
use app\model\User;
/*
 * 用户行为操作记录类
 */
class SystemOperateLog extends Model
{

    protected $opData = [
        'uid',
        'model',
        'operate',
        'operate_date',
        'ip'
    ];

    public function user()
    {
        return $this->hasOne('user','id','uid')->bind(['username', 'nickname']);
    }
    /**
     * @param $uid
     * @param $model
     * @param $operate
     * @return bool
     */
    public function addOperate($uid, $model, $operate)
    {
        return $this->allowField($this->opData)->save([
            'uid'=>$uid,
            'model'=>$model,
            'operate'=>$operate,
            'operate_date'=>time(),
            'ip'=>$this->getIp()
        ]);
    }

    /**
     * 查询日志列表
     * @param $where
     * @param int $pageNum
     * @param int $page
     * @return \app\model\SystemOperateLog[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getLogModelList($where, int $pageNum,int $page)
    {
        return $this->with('user')->whereLike ('operate','%'.$where.'%')->page($page,$pageNum)->order('operate_date','DESC')->select();
    }

    public function getWhereCount($where)
    {
        return $this->whereLike ('operate','%'.$where.'%')->count();
    }

    /**
     * @param $value
     * @return false|string
     */
    public function setOperateDateAttr($value)
    {
        return date('Y-m-d,H:i:s',$value);
    }

    /**
     * @return mixed
     */
    private function getIp()
    {
        return $_SERVER["REMOTE_ADDR"];
    }

}